var fs = require('fs')
  , path = require('path')
  , less = require('less')
  , glob = require('glob')
  , gutil = require('gulp-util');




function lessMiddleware(options){

  var sourceDir = path.join(
    options.cwd,
    options.sourceDir
  );

  return function(req,res,next){
    res.contentType('text/css');
    var sourceCode = fs.readFileSync(
      path.join(
        sourceDir,
        req.url.replace(/\.css$/,'.less')
      )
    ).toString();
    less.render(sourceCode,{
      paths: options.paths
    },function (err, output) {
      if(err){
        var errContent = JSON.stringify(err);
        res.end('body:before { display:block;content:\''+errContent+'\';}');
        console.error(err);
      }else{
        res.end(output.css);
      }
    });
  }
}

module.exports = function(server){

  server.get('/js/bluewareui-seed-:version.js',function(req,res){
    res.set('Content-Type', 'application/javascript');
    res.end(
      fs.readFileSync('node_modules/requirejs/require.js').toString()
    + fs.readFileSync('config/config.js').toString()
    );
  });

  server.get('/js/mobile/:module/main-:version.js',function(req,res){
    res.redirect('./main.js');
  });

  server.get('/css/style-:version.css',function(req,res){
    res.redirect('./style.css')
  });

  server.use('/css',lessMiddleware({
    cwd: process.cwd(),
    sourceDir: 'style',
    paths:[
      path.join(process.cwd(), 'style'),
      path.join(process.cwd(), 'node_modules/'),
      path.join(process.cwd(), 'node_modules/fed-lib/less')
    ]
  }))

};
